<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>用户--添加</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="/components/treetable-lay/assets/layui/css/layui.css">
    <script src='/base/js/Convert_Pinyin.js'></script>
    <script src="/manage/js/app.js"></script>
</head>
<body>
<style>
    .layui-form-item .layui-input-inline {
        width: 300px;
    !important;
    }
</style>

<div class="layui-form" lay-filter="layuiadmin-app-form-list" id="layuiadmin-app-form-list"
     style="padding: 20px 30px 0 0;">

    <div class="layui-form-item">
        <label class="layui-form-label">终端</label>
        <div id="terminal" class="layui-input-block">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">头像</label>
        <span class="layui-input-inline">
            <button type="button" class="layui-btn layui-btn-danger" id="test7" style="width: 180px"><i class="layui-icon"></i>上传头像</button>
            <!-- 预览图,上传图片后展示 --><!--圆  style='border-radius: 30px;width: 35px;height: 35px;'-->
            <img src="" title="" id="headImg" style="border-radius: 180px;width: 180px;height: 180px; margin-top: 5%">
            <!-- 隐藏input,最后添加数据 -->
            <input type="text" id="head" name="head" lay-verify="imgHead" placeholder="请输入" autocomplete="off" hidden>
        </span>
        <!-- 提示 -->
        <font class="layui-word-aux">
            头像必须小于 500KB
        </font>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">姓名</label>
        <div class="layui-input-inline">
            <input type="text" id="fullName" name="fullName" lay-verify="required" onkeyup="updUsername()" placeholder="请输入" autocomplete="off"
                   class="layui-input">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">账号</label>
        <div class="layui-input-inline">
            <input type="text" id="username" name="username" lay-verify="required" placeholder="请输入" autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">手机号</label>
        <div class="layui-input-inline">
            <input type="text" id="phone" name="phone" lay-verify="required" placeholder="请输入" autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">密码</label>
        <div class="layui-input-inline">
            <input type="text" id="password" name="password" lay-verify="required" placeholder="请输入" autocomplete="off"
                   class="layui-input">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">性别</label>
        <div id="gender" class="layui-input-block">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">年龄</label>
        <div class="layui-input-inline">
            <input type="text" id="age" name="age" lay-verify="required" placeholder="请输入" autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">地址</label>
        <div class="layui-input-inline">
            <input type="text" id="address" name="address" lay-verify="required" placeholder="请输入" autocomplete="off"
                   class="layui-input">
        </div>
    </div>
    <!--    <div class="layui-form-item">-->
    <!--        <label class="layui-form-label">职位</label>-->
    <!--        <div class="layui-input-inline">-->
    <!--            <select id="position" name="position" lay-verify="" lay-filter="gender">-->
    <!--            </select>-->
    <!--        </div>-->
    <!--    </div>-->

    <div class="layui-form-item">
        <label class="layui-form-label">部门</label>
        <div class="layui-input-inline">
            <div class="rc-cascader">
                <input type="text" id="organId" name="organId" value="" style="display: none;"/>
            </div>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">职位</label>
        <div id="position" class="layui-input-block">
        </div>
    </div>

    <div class="layui-form-item" pane="">
        <label class="layui-form-label">角色</label> <!-- 默认选中： checked="   禁用： disabled=""  -->
        <div id="roleIds" class="layui-input-block">
        </div>
    </div>

    <div class="layui-form-item layui-hide">
        <input type="button" lay-submit lay-filter="layuiadmin-app-form-submit" id="layuiadmin-app-form-submit"
               value="确认添加">
        <input type="button" lay-submit lay-filter="layuiadmin-app-form-edit" id="layuiadmin-app-form-edit"
               value="确认编辑">
    </div>
</div>

<script>
    // layui.config({
    //     base: '../components/treetable-lay/module/' //静态资源所在路径
    // }).extend({
    //     treetable: 'treetable-lay/treetable'
    //
    //
    layui.config({
        base: '../components/cascader/ext/' //静态资源所在路径
    }).extend({
        cascader: 'cascader/cascader'
    }).use(['jquery', 'cascader', 'form', 'upload'], function () {

        init();
        initOrgan()
        upload();
        formSubmit();
    });


    function init() {
        // 默认隐藏头像
        $("#headImg").hide();
        $("#gender").html(Dict.getDictRadio(Enums.Base.Gender, "gender", null));       // 性别
        $("#position").html(Dict.getDictRadio(Enums.Admin.Position, "position", null)); // 职位
        $("#terminal").html(Dict.getDictRadio(Enums.Admin.Terminal, "terminal")); // 终端
        // 获取角色列表
        let roleList = Ajax.get(parent.roleFindUserRole.replace("{userId}", "")).data.records;
        let roleHtml = "";
        let roleHtmlTemplates = "<input type='checkbox' name='{name}' value='{value}' lay-skin='primary' title='{title}' {checked}>" +
            "<div class='layui-unselect layui-form-checkbox' lay-skin='primary'>" +
            "<span>{title}</span><i class='layui-icon layui-icon-ok'></i></div>";
        $.each(roleList, function (index) {
            roleHtml += roleHtmlTemplates
                .replace("{name}", "roleId")
                .replace("{title}", roleList[index].name)
                .replace("{value}", roleList[index].id)
                .replace("{checked}", "")
        });
        $("#roleIds").html(roleHtml);   // 角色
        // 刷新,否则select可能不生效
        layui.form.render();
    }


    function initOrgan() {
        var areaTree = Ajax.get(parent.organListUrl).data;
        // *elem：HTMLElement对象，例如：$('input[name=example]')[0]
        // *options：Array 数据
        // onChange: Function(curr, value) curr: 选中值，value：所有值(当multiple为true有效)
        // multiple：boolean 是否开启多选，默认 Flase
        // collapseTags：boolean 是否折叠选项（multiple 开启时有效），默认 True
        // showAllLevels: boolean 是否查看所有级名，默认 True
        // props：数据对象解析，默认：{ label: 'label', value: 'value', children: 'children' }
        // placeholder：String 无选择文本填充 默认 请选择
        // separator：String 显示文本的分隔符号（showAllLevels开启时生效） 默认 /
        // valueSeparator：String 选择值的级联分隔符号 默认 ,
        // groupSeparator：String 多选时选择值的组分隔符号 默认 |
        var $ = layui.jquery, cascader = layui.cascader;
        cascader.render({
            elem: $('input[name=organId]')[0],
            options: areaTree,
            // onChange: function(curr, value){
            //     console.log(curr+ value);
            // },
            multiple: false,
            showAllLevels: true,
            collapseTags: false,
            valueSeparator: ",", //String 选择值的级联分隔符号 默认 ,
            placeholder: "无",
            props: {
                label: 'name',
                value: 'id',
                children: 'organs'
            },
            //options: JSON.parse(areaTree),
        });
    }



    function upload() {
        //文件上传--设定文件大小限制
        layui.upload.render({
            elem: '#test7'
            , url: uploadPath + '?filePath=image/head/' //改成您自己的上传接口
            , size: 500 //限制文件大小，单位 KB
            , headers: {"TOKEN": getGlobalHeaders()}
            , done: function (res) {
                //如果上传失败
                if (res.code !== 200) {
                    return layer.msg('上传失败-' + res.msg);
                }
                $("#headImg").attr("src", res.data);
                $("#headImg").attr("title", res.date);
                $("#headImg").show();
                //赋值input
                $("#head").val(res.data);
                console.log(res);
                layer.msg('上传成功');
            }
        });
    }

    //监听提交
    function formSubmit() {
        layui.form.on('submit(layuiadmin-app-form-submit)', function (data) {
            // 放入角色数据
            let roles_box = [];
            $('input[type=checkbox]:checked').each(function () {
                roles_box.push($(this).val());
            });
            data.field.roleIds = roles_box;
            //
            let result = Ajax.post(parent.userUrl, data.field);
            let index = parent.layer.getFrameIndex(window.name);
            parent.layer.close(index);
            parent.layer.msg(result.msg);
            //重载表格
            parent.xijiaRenderTable();
            //刷新页数信息
            parent.xijiaLayPage();

        });
    }


    /**
     * 输入姓名->生成账号
     */
    function updUsername() {
        let fullName = $("#fullName").val();
        //获取全写拼音（调用js中方法）
        let username = pinyin.getFullChars(fullName);
        $("#username").val(username.toLowerCase());
        //获取全写拼音（调用js中方法）
        // let username = pinyin.getFullChars(fullName);
        //获取简写拼音（调用js中方法）
        // var easyName = pinyin.getCamelChars(chinaName);
        // //给两个文本框赋值
        // $('#fullName').val(fullName);
        // $('#easyName').val(easyName);
    }
</script>
</body>
</html>